/*
 * @Description:
 * @Autor: fage
 * @Date: 2022-06-06 15:10:14
 * @LastEditors: fage
 * @LastEditTime: 2022-07-07 10:27:48
 */
"use strict";
const db = require("../utils/db");
const common = require("../utils/common");
const path = require("path");

module.exports = function (req, res, next) {
  let funs = {
    list: list,
    save: save,
    del: del,
    getDir: getDir,
  };
  let ret = {
    msg: "ok",
    data: [],
  };
  let f = funs[req.body.action];
  if (f) {
    f(ret, req, res);
  } else {
    ret.msg = "action(" + req.body.action + ")未定义";
    res.json(ret);
  }
};
function list(ret, req, res) {
  res.json({ msg: "ok", data: db.get("websites") });
}

function del(ret, req, res) {
  const id = req.body.id;
  const list = db.get("websites");
  const i = list.findIndex((t) => t.id == id);
  list.splice(i, 1);
  db.set("websites", list);
  db.sync();
  res.json({ msg: "ok", data: list });
}
function save(ret, req, res) {
  let id = "",
    obj;
  const list = db.get("websites");
  let exec = req.body.exec;
  exec = exec.split("\n");
  let exec2 = req.body.exec2;
  exec2 = exec2.split("\n");
  if (req.body.id) {
    id = req.body.id;
    const i = list.findIndex((t) => t.id == id);
    obj = list[i];
    obj.id = req.body.password;
    obj.password = req.body.password;    
    obj.waitExecComplete = req.body.waitExecComplete;
    obj.path = req.body.path;
    obj.deployKeyword = req.body.deployKeyword;
    obj.exec = exec;
    obj.deployKeyword2 = req.body.deployKeyword2;
    obj.exec2 = exec2;
  } else {
    obj = {
      id: req.body.password,
      password: req.body.password,      
      waitExecComplete: req.body.waitExecComplete,
      path: req.body.path,
      deployKeyword: req.body.deployKeyword,
      exec,
      deployKeyword2: req.body.deployKeyword2,
      exec2,
    };
    list.push(obj);
  }
  db.set("websites", list);
  db.sync();
  res.json({ msg: "ok", data: list });
}
function getDir(ret, req, res) {
  if (!req.body.dir) {
    req.body.dir = "/";
  }
  let dir = path.join(req.body.dir, "/");
  console.log("req.body.dir", dir);
  res.json({ msg: "ok", data: common.getDir(dir) });
}
